package com.arpa.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.entity.Party;
import com.arpa.ntocc.common.service.IPartyService;
import com.arpa.wms.cache.WarehouseCache;
import com.arpa.wms.common.util.DateUtil;
import com.arpa.wms.common.util.OrderIdGeneratorUtil;
import com.arpa.wms.domain.consts.CodeConst;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.dto.*;
import com.arpa.wms.domain.entity.Delivery;
import com.arpa.wms.domain.entity.PackBillingMethod;
import com.arpa.wms.domain.entity.PackTask;
import com.arpa.wms.domain.entity.PackTaskItem;
import com.arpa.wms.domain.enums.JobTypeEnum;
import com.arpa.wms.domain.enums.PackTaskStatusEnum;
import com.arpa.wms.domain.vo.*;
import com.arpa.wms.mapper.PackTaskMapper;
import com.arpa.wms.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static com.arpa.wms.domain.consts.NumConst.NUM_ZERO;

/**
 * @author: rfwang
 * @Date 2021/06/29
 * @Description:
 */
@Service
@Log4j2
public class PackTaskServiceImpl extends ServiceImpl<PackTaskMapper, PackTask> implements IPackTaskService {

    public static final String SHIPMENT_CODE = "shipmentCode";
    public static final String CARRIER_CODE = "carrierCode";
    public static final String CARRIER_NAME = "carrierName";
    public static final String COUNT = "count";
    public static final String TOTAL_NUM = "totalNum";

    @Autowired
    private IPackBillingMethodService packBillingMethodService;
    @Autowired
    private WarehouseCache warehouseCache;
    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private ShipmentCache shipmentCache;
    @Autowired
    private PartyCache partyCache;
    @Autowired
    private IPackTaskItemService packTaskItemService;
    @Autowired
    private IPartyService partyService;
//    @Autowired
//    private IPointsItemService pointsItemService;
    @Autowired
    @Lazy
    private IPrepackagedService prepackagedService;



    /**
     * 打包任务下发
     * @param packTaskDTO
     * @return Result
     */
    @Override
    @Transactional
    public Result packTaskIssue(PackTaskDTO packTaskDTO) {
        packTaskDTO.setGroupCode(UserUtil.getBranchCode());
        //1.检验作业类型及计费方式
        validatePackData(packTaskDTO);
        //2.更新下发任务状态
        handleTaskStatus(packTaskDTO);
        //3.生成下发任务及明细
        generatePackTask(packTaskDTO);
        return Result.ok();
    }

    private void validatePackData(PackTaskDTO packTaskDTO) {
        //作业类型校验
        validateJobType(packTaskDTO);
        //获取仓库信息
        String warehouseCode = packTaskDTO.getDeliveryList().get(NUM_ZERO).getWarehouseCode();
        //计费方式校验并判断是否生成打包计费方式信息
        PackBillingMethodDTO packBillingMethodDTO = new PackBillingMethodDTO();
        BeanUtil.copyProperties(packTaskDTO,packBillingMethodDTO);
        packBillingMethodDTO.setPartyCode(packTaskDTO.getPartyCode());
        packBillingMethodDTO.setStaffName(packTaskDTO.getStaffName());
        packBillingMethodDTO.setWarehouseCode(warehouseCode);
        validatePackBillingMethod(packBillingMethodDTO);

    }

    private void validateJobType(PackTaskDTO packTaskDTO) {
        List<Delivery> deliveryList = packTaskDTO.getDeliveryList();
        if (JobTypeEnum.PACK.getValue().equals(packTaskDTO.getJobType())) {
            long packCount = deliveryList.stream().filter(item -> item.getPackIssue() == 1).count();
            if (packCount > NUM_ZERO) {
                log.error("下发任务含有已打包任务，任务下发失败！！！");
                throw new ServiceException("下发任务含有已打包任务，任务下发失败！！！");
            }
        }
        if (JobTypeEnum.PASTE.getValue().equals(packTaskDTO.getJobType())) {
            long packCount = deliveryList.stream().filter(item -> item.getPasteIssue() == 1).count();
            if (packCount > NUM_ZERO) {
                log.error("下发任务含有已贴单任务，任务下发失败！！！");
                throw new ServiceException("下发任务含有已贴单任务，任务下发失败！！！");
            }
        }
        if (JobTypeEnum.PACK_PASTE.getValue().equals(packTaskDTO.getJobType())) {
            long packCount = deliveryList.stream().filter(item -> item.getPackIssue() == 1 || item.getPasteIssue() == 1).count();
            if (packCount > NUM_ZERO) {
                log.error("下发任务含有已打包或者已贴单任务，任务下发失败！！！");
                throw new ServiceException("下发任务含有已打包或者已贴单任务，任务下发失败！！！");
            }
        }
    }

    @Override
    public void validatePackBillingMethod(PackBillingMethodDTO packBillingMethodDTO) {

        PackBillingMethodVO packBillingMethodVO = packBillingMethodService.getPackBillingInfo(packBillingMethodDTO);
        //如果存在计费信息
        //①计费方式不一致，提示：计费方式与已维护数据不一致
        //②计费方式一致，单价不一致更新单价
        //3计费方式一致，单价一致，不更新数据；
        if (null != packBillingMethodVO) {
            if (!packBillingMethodVO.getBillingMethod().equals(packBillingMethodDTO.getBillingMethod())) {
                throw new ServiceException("计费方式与已维护数据不一致");
            }
            if (packBillingMethodVO.getBillingPrice().compareTo(packBillingMethodDTO.getBillingPrice()) != NUM_ZERO) {
                packBillingMethodService.update(new LambdaUpdateWrapper<PackBillingMethod>().eq(PackBillingMethod::getCode, packBillingMethodVO.getCode())
                        .eq(PackBillingMethod::getGroupCode,UserUtil.getBranchCode())
                        .set(PackBillingMethod::getBillingPrice, packBillingMethodDTO.getBillingPrice())
                        .set(PackBillingMethod::getGmtModified, LocalDateTime.now())
                        .set(PackBillingMethod::getModifiedBy, partyCache.translate(UserUtil.getCode())));
            }
        }
//        如果不存在，新增一条打包计费方式记录
        if (null == packBillingMethodVO) {
            Party party = partyService.getOne(new LambdaQueryWrapper<Party>().eq(Party::getCode, packBillingMethodDTO.getPartyCode()).eq(Party::getBranchCode,UserUtil.getBranchCode()));
            String warehouseCode = packBillingMethodDTO.getWarehouseCode();
            PackBillingMethod packBillingMethod = new PackBillingMethod();
            BeanUtil.copyProperties(packBillingMethodDTO,packBillingMethod,false);
            packBillingMethod.setCode(IdUtil.fastSimpleUUID());
            packBillingMethod.setEmploymentType(party.getEmploymentType());
            packBillingMethod.setStaffPhone(party.getCode());
            packBillingMethod.setGroupCode(UserUtil.getBranchCode());
            packBillingMethod.setWarehouseCode(warehouseCode);
            packBillingMethod.setWarehouseName(warehouseCache.translate(warehouseCode));
            packBillingMethod.setJobTime(DateUtil.getYearMonthDay());
            packBillingMethod.setOutsourcer(party.getOutsourcer());
            packBillingMethodService.save(packBillingMethod);
        }
    }

    private void handleTaskStatus(PackTaskDTO packTaskDTO) {
        List<Delivery> deliveryList = packTaskDTO.getDeliveryList();
        List<String> deliveryCodes = deliveryList.stream().map(Delivery::getCode).collect(Collectors.toList());
        DeliveryDTO deliveryDTO = new DeliveryDTO();
        deliveryDTO.setDeliveryCodes(deliveryCodes);
        deliveryDTO.setGroupCode(UserUtil.getBranchCode());
        if (JobTypeEnum.PACK.getValue().equals(packTaskDTO.getJobType())) {
            deliveryDTO.setPackIssue(NumConst.NUM_ONE);
        }
        if (JobTypeEnum.PASTE.getValue().equals(packTaskDTO.getJobType())) {
            deliveryDTO.setPasteIssue(NumConst.NUM_ONE);
        }
        if (JobTypeEnum.PACK_PASTE.getValue().equals(packTaskDTO.getJobType())) {
            deliveryDTO.setPackIssue(NumConst.NUM_ONE);
            deliveryDTO.setPasteIssue(NumConst.NUM_ONE);
        }
        deliveryService.updateByCodes(deliveryDTO);
    }

    private void generatePackTask(PackTaskDTO packTaskDTO) {
        List<Delivery> deliveryList = packTaskDTO.getDeliveryList();
        List<String> deliveryCodes = deliveryList.stream().map(Delivery::getCode).collect(Collectors.toList());
        List<Map<String,Object>> maps = deliveryService.queryPackTaskGroupInfo(deliveryCodes);
        if (IterUtil.isEmpty(maps)) {
            log.error("生成打包任务找不到符合条件的订单信息，订单号:{}", deliveryCodes);
            throw new ServiceException("生成打包任务找不到符合条件的订单信息，订单号:" + deliveryCodes);
        }
        //生成出库任务明细
        List<PackTaskItem> itemList = generatePackTaskItem(deliveryList);
        for (Map<String,Object> map : maps) {
            PackTask packTask = new PackTask();
            String shipmentCode = MapUtil.getStr(map, SHIPMENT_CODE);
            String carrierCode = MapUtil.getStr(map, CARRIER_CODE);
            String carrierName = MapUtil.getStr(map, CARRIER_NAME);
            String warehouseCode = MapUtil.getStr(map, CodeConst.WAREHOUSE_CODE);
            Integer orderQuantity = MapUtil.getInt(map, COUNT);
            BigDecimal goodsQuantity = MapUtil.get(map, TOTAL_NUM,BigDecimal.class);
            BeanUtil.copyProperties(packTaskDTO,packTask,false);
            // 使用PACK+日期+流水号
            String codePrefix = OrderIdGeneratorUtil.OrderTypeEnum.PACK + DateUtil.getDate();
            packTask.setCode(codePrefix + OrderIdGeneratorUtil.getAutoIncrementIndex(codePrefix,3));
            packTask.setWarehouseCode(warehouseCode);
            packTask.setWarehouseName(warehouseCache.translate(warehouseCode));
            packTask.setShipmentCode(shipmentCode);
            packTask.setShipmentName(shipmentCache.translate(shipmentCode));
            packTask.setGroupCode(UserUtil.getBranchCode());
            packTask.setOrderType(CommonConst.NORMAL);
            packTask.setCarrierCode(carrierCode);
            packTask.setCarrierName(carrierName);
            packTask.setOrderQuantity(orderQuantity);
            packTask.setGoodsQuantity(goodsQuantity);
            packTask.setStatus(PackTaskStatusEnum.WAITING.getValue());
            //按单的或许没有承运商
            List<String> filterDeliveryCodes = null;
            if(StringUtils.isBlank(carrierCode)){
                 filterDeliveryCodes = deliveryList.stream().filter(e -> e.getShipmentCode().equals(shipmentCode))
                        .map(Delivery::getCode).collect(Collectors.toList());
            }else{
                filterDeliveryCodes = deliveryList.stream().filter(e -> e.getShipmentCode().equals(shipmentCode) && e.getCarrierCode().equals(carrierCode))
                        .map(Delivery::getCode).collect(Collectors.toList());
            }
            for (PackTaskItem e : itemList) {
                if (filterDeliveryCodes.contains(e.getSourceCode())) {
                    e.setPackTaskCode(packTask.getCode());
                }
            }
            this.save(packTask);
        }
        packTaskItemService.saveBatch(itemList);
    }

    private List<PackTaskItem> generatePackTaskItem(List<Delivery> deliveryList) {
        List<PackTaskItem> itemList = Lists.newArrayList();
        deliveryList.forEach(info -> {
            PackTaskItem item = new PackTaskItem();
            item.setCode(IdUtil.simpleUUID());
            item.setSourceCode(info.getCode());
            item.setGmtCreated(LocalDateTime.now());
            item.setCreatedBy(UserUtil.getCode());
            item.setCreatedName(partyCache.translate(UserUtil.getCode()));
            item.setGroupCode(UserUtil.getBranchCode());
            itemList.add(item);
        });
        return itemList;
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean save(PackTask entity) {
        if (StringUtils.isBlank(entity.getCode())) {
            entity.setCode(IdUtil.simpleUUID());
        }
        if (StringUtils.isBlank(entity.getCreatedBy())) {
            entity.setCreatedBy(UserUtil.getCode());
            entity.setCreatedName(partyCache.translate(UserUtil.getCode()));
        }
        return super.save(entity);
    }

    /**
     * 查询合计,包含总数
     * @param packTaskDTO
     * @return
     */
    @Override
    public PackTaskVO queryListSum(PackTaskDTO packTaskDTO) {
        packTaskDTO.setGroupCode(UserUtil.getBranchCode());
        return baseMapper.queryListSum(packTaskDTO);
    }

    /**
     * 查询列表
     * @param packTaskDTO
     * @return
     */
    @Override
    public List<PackTaskVO> queryList(PackTaskDTO packTaskDTO) {
        packTaskDTO.setGroupCode(UserUtil.getBranchCode());
        return baseMapper.queryList(packTaskDTO);
    }

    /**
     * 打包任务完成
     * @param dtoList
     * @return Result
     */
    @Override
    public Result complete(List<PackTaskDTO> dtoList,String warehouseCode) {
        String groupCode = UserUtil.getBranchCode();
        //校验打包状态
        validatePackStatus(dtoList);
        //回写打包数量及状态
        handlePackTaskInfo(dtoList);
        //回写预打包打包完成数量
        handlePrepackagedInfo(dtoList);
        //异步增加积分明细
//        pointsItemService.packTaskCompleteAddPointsItem(dtoList,warehouseCode,groupCode);
        return Result.ok();
    }

    private void validatePackStatus(List<PackTaskDTO> dtoList) {
        long count = dtoList.stream().filter(item -> PackTaskStatusEnum.COMPLETED.getValue().equals(item.getStatus())).count();
        if (count > NUM_ZERO) {
            log.error("打包任务状态必须是待打包，请确认！！！");
            throw new ServiceException("打包任务状态必须是待打包，请确认！！！");
        }
    }

    private void handlePackTaskInfo(List<PackTaskDTO> dtoList) {
        PackTaskDTO packTaskDTO = new PackTaskDTO();
        List<String> packTaskCodes = dtoList.stream().map(PackTaskDTO::getCode).collect(Collectors.toList());
        packTaskDTO.setStatus(PackTaskStatusEnum.COMPLETED.getValue());
        packTaskDTO.setGmtFinish(DateUtil.getYearMonthDay());
        packTaskDTO.setPackTaskCodes(packTaskCodes);
        packTaskDTO.setGroupCode(UserUtil.getBranchCode());
        //更新打包任务信息
        updateByCodes(packTaskDTO);
    }

    /**
     * 根据codes更新实体
     * @param dto
     * @return
     */
    @Override
    public int updateByCodes(PackTaskDTO dto){
        dto.setModifiedName(partyCache.translate(UserUtil.getCode()));
        dto.setModifiedBy(UserUtil.getCode());
        dto.setGmtModified(LocalDateTime.now());
        return this.baseMapper.updateByCodes(dto);
    }

    /**
     * 获取打包单详情
     * @param code
     * @return
     */
    @Override
    public PackTaskVO getVOWithItemByCode(String code){
        String groupCode = UserUtil.getBranchCode();
        PackTask packTask = this.getOne(new LambdaQueryWrapper<PackTask>().eq(PackTask::getCode, code).eq(PackTask::getGroupCode,groupCode));
        PackTaskVO packTaskVO = new PackTaskVO();
        BeanUtil.copyProperties(packTask,packTaskVO);
        PackTaskItemDTO dto = new PackTaskItemDTO();
        dto.setPackTaskCode(code);
        List<String> sourceCodes = packTaskItemService.list(new LambdaQueryWrapper<PackTaskItem>()
                .eq(PackTaskItem::getPackTaskCode,packTask.getCode())
                .eq(PackTaskItem::getGroupCode,groupCode))
                .stream().map(e-> e.getSourceCode()).collect(Collectors.toList());
        List<PackTaskItemVO> packTaskItemVOList = Lists.newArrayList();
        if (IterUtil.isEmpty(sourceCodes)) {
            throw new ServiceException("任务单["+code+"]没有明细，请确认");
        }
        if (CommonConst.PREPACKAGED.equals(packTask.getOrderType())) {
            //预打包逻辑处理
            packTaskVO.setOrderType(CommonConst.PREPACKAGED);
            PrepackagedVO prepackagedVO = prepackagedService.getVOByCode(sourceCodes.get(NUM_ZERO));
            PackTaskItemVO itemVO = new PackTaskItemVO();
            itemVO.setPrepackagedCode(prepackagedVO.getCode());
            //由于预打包任务明细和普通打包任务明细都在一个页面展示，所以打包单号都叫deliveryCode
            itemVO.setDeliveryCode(prepackagedVO.getCode());
            itemVO.setPlanPackQuantity(packTask.getPackageQuantity());
            itemVO.setGoodsSortQuantity(new BigDecimal(prepackagedVO.getTypeQuantity().toString()));
            itemVO.setTotalNum(new BigDecimal(packTask.getGoodsQuantity().toString()));
            itemVO.setPackQuantity(prepackagedVO.getPackQuantity());
            packTaskItemVOList.add(itemVO);
            List<PrepackagedItemWithDistributionVO> prepackagedItemWithDistributionVOS = prepackagedVO.getPrepackagedItemWithDistributionVOList();
            List<DeliveryItemWithDistributionVO> deliveryItemWithDistributionVOS = prepackagedItemWithDistributionVOS.stream().map(info -> {
                DeliveryItemWithDistributionVO distributionVO = new DeliveryItemWithDistributionVO();
                BeanUtil.copyProperties(info,distributionVO);
                distributionVO.setPackQuantity(prepackagedVO.getPackQuantity());
                return distributionVO;
            }).collect(Collectors.toList());
            packTaskVO.setPackTaskItemVOList(packTaskItemVOList);
            packTaskVO.setDeliveryItemWithDistributionVOList(deliveryItemWithDistributionVOS);
            packTaskVO.setPrepackagedCode(prepackagedVO.getCode());
        } else {
                //普通打包逻辑处理;
                packTaskVO.setOrderType(CommonConst.NORMAL);

                List<Delivery> deliveryList = deliveryService.list(new LambdaQueryWrapper<Delivery>()
                        .select(Delivery::getOrderNum, Delivery::getCode, Delivery::getCarrierCode,Delivery::getCarrierName, Delivery::getWaybillCode,
                                Delivery::getIsvCode, Delivery::getGoodsSortQuantity, Delivery::getTotalNum)
                        .in(Delivery::getCode, sourceCodes)
                        .eq(Delivery::getGroupCode,groupCode))
                        .stream()
                        .sorted(Comparator.comparing(Delivery::getOrderNum))
                        .collect(Collectors.toList());

                DeliveryVO deliveryVO = deliveryService.getVOByCode(deliveryList.get(NUM_ZERO).getCode());

                if (IterUtil.isNotEmpty(deliveryList)) {
                    List<DeliveryItemWithDistributionVO> itemWithDistributionVOS = deliveryVO.getDeliveryItemWithDistributionVOList()
                            .stream().peek(info -> {
//                                info.setPlanPackQuantity(NUM_ONE);
                                info.setCombinationQuantity(info.getTotalNum());
                                if (PackTaskStatusEnum.WAITING.getValue().equals(packTaskVO.getStatus())) {
                                    info.setPackQuantity(NUM_ZERO);
                                } else {
                                    info.setPackQuantity(NUM_ONE);
                                }
                            }).collect(Collectors.toList());
                    packTaskVO.setDeliveryItemWithDistributionVOList(itemWithDistributionVOS);
                }
                packTaskItemVOList = deliveryList.stream().map(info -> {
                    PackTaskItemVO itemVO = new PackTaskItemVO();
                    BeanUtil.copyProperties(info, itemVO);
                    itemVO.setPlanPackQuantity(NUM_ONE);
                    if (PackTaskStatusEnum.WAITING.getValue().equals(packTaskVO.getStatus())) {
                        itemVO.setPackQuantity(NUM_ZERO);
                    } else {
                        itemVO.setPackQuantity(NUM_ONE);
                    }
                    return itemVO;
                }).collect(Collectors.toList());
            }

            if (IterUtil.isNotEmpty(packTaskItemVOList)) {
                long count = packTaskItemVOList.stream().filter(e -> e.getOrderNum() == null).count();
                if (count > 0) {
                    packTaskVO.setPackTaskItemVOList(packTaskItemVOList);
                } else {
                    packTaskVO.setPackTaskItemVOList(packTaskItemVOList.stream().sorted(Comparator.comparing(PackTaskItemVO::getOrderNum)).collect(Collectors.toList()));
                }
            }

        return packTaskVO;
    }

    /**
     * 获取打印信息
     * @param packTaskCodes
     * @return
     */
    @Override
    public List<PackTaskVO> getPintInfo(List<String> packTaskCodes){
        return packTaskCodes.stream().map(code -> {
            return getVOWithItemByCode(code);
        }).collect(Collectors.toList());
    }


    /**
     * 计费单价
     * @return
     */
    @Override
    public BigDecimal billingPrice() {
        BigDecimal billingPrice = baseMapper.billingPrice(UserUtil.getBranchCode());
        return billingPrice;
    }

    @Transactional(rollbackFor = {Exception.class})
    public void handlePrepackagedInfo(List<PackTaskDTO> dtoList) {
        String modifiedBy = UserUtil.getCode();
        String modifiedName = partyCache.translate(modifiedBy);
        LocalDateTime updateTime = LocalDateTime.now();
        //根据预打包单号进行分组
        Map<String, List<PackTaskDTO>> listMap = dtoList.stream().collect(Collectors.groupingBy(PackTaskDTO::getPrepackagedCode));
        for (Map.Entry<String,List<PackTaskDTO>> listEntry: listMap.entrySet()) {
            PrepackagedDTO prepackagedDTO = new PrepackagedDTO();
            prepackagedDTO.setCode(listEntry.getKey());
            Integer packageQuantity = 0;
            for (PackTaskDTO packTaskDTO : listEntry.getValue()) {
                if (packTaskDTO.getPackageQuantity() != null) {
                    packageQuantity = packageQuantity + packTaskDTO.getPackageQuantity();
                }
            }
            prepackagedDTO.setPackageQuantity(packageQuantity);
            prepackagedDTO.setModifiedBy(modifiedBy);
            prepackagedDTO.setModifiedName(modifiedName);
            prepackagedDTO.setGmtModified(updateTime);
            prepackagedDTO.setGroupCode(UserUtil.getBranchCode());
            prepackagedService.updatePackedQuantity(prepackagedDTO);
        }
    }

    /**
     * 奖惩录入确认提交
     * @param packTask
     * @return Result
     */
    @Override
    public Result rewardPunishSubmit(PackTask packTask){
        String groupCode = UserUtil.getBranchCode();
        //必填项校验
        validateParams(packTask);
        //生成费用明细后，禁止在进行奖惩录入
        int genCostsNum = this.count(new LambdaQueryWrapper<PackTask>()
                .in(PackTask::getCode, packTask.getPackTaskCodes())
                .eq(PackTask::getGroupCode,groupCode)
                .eq(PackTask::getGenCosts, NUM_ONE));
        if (genCostsNum > 0) {
            throw new ServiceException("所选任务中含有已生成费用明细的任务，不能进行奖惩录入");
        }

        List<PackTask> packTasks = baseMapper.selectList(new QueryWrapper<PackTask>().lambda().in(PackTask::getCode, packTask.getPackTaskCodes()).eq(PackTask::getGroupCode,groupCode));
        List<PackTask> saleWithoutCarrierNameList = packTasks.stream().filter(e -> e.getStatus().equals(PackTaskStatusEnum.WAITING.getValue())).collect(Collectors.toList());
        if(ObjectUtil.isNotNull(saleWithoutCarrierNameList) && saleWithoutCarrierNameList.size() > 0){
            throw new ServiceException("所选任务中含有待打包的任务，不能进行奖惩录入");
        }

        String modifiedBy = UserUtil.getCode();
        String modifiedName = partyCache.translate(modifiedBy);
        LocalDateTime gmtModified = LocalDateTime.now();
        this.update(new LambdaUpdateWrapper<PackTask>().in(PackTask::getCode, packTask.getPackTaskCodes())
                .eq(PackTask::getGroupCode,groupCode)
                .set(PackTask::getRewardAmount, packTask.getRewardAmount())
                .set(PackTask::getPunishAmount, packTask.getPunishAmount())
                .set(PackTask::getRemarks,packTask.getRemarks())
                .set(PackTask::getModifiedBy, modifiedBy)
                .set(PackTask::getModifiedName, modifiedName)
                .set(PackTask::getGmtModified, gmtModified));
        return Result.ok();
    }

    private void validateParams(PackTask packTask){
        if (null == packTask) {
            throw new ServiceException("入参打包任务信息不能为空");
        }
        if (IterUtil.isEmpty(packTask.getPackTaskCodes())) {
            throw new ServiceException("勾选的任务不能为空");
        }

        BigDecimal rewardAmount = packTask.getRewardAmount() != null ? packTask.getRewardAmount() : BigDecimal.ZERO;
        BigDecimal punishAmount = packTask.getPunishAmount() != null ? packTask.getPunishAmount() : BigDecimal.ZERO;

        if (rewardAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new ServiceException("奖励金额不能为负数");
        }
        if (punishAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new ServiceException("惩罚金额不能为负数");
        }
        //对奖惩金额重新赋值，如果数据为空，则给其默认值0
        packTask.setRewardAmount(rewardAmount);
        packTask.setPunishAmount(punishAmount);
    }

}
